<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Session_manager {
	
	var $auth_redirect = true;
	var $user = array();
	var $session_path = "./sessions";
	var $session_key = "aKdi#1w9eN&sd73";

	function __construct($auth=true, $path='') {
		$this->auth_redirect = $auth; 
		if ($path) $this->session_path=$path;
		$this->manage();
	}
	
	function manage() {
		if (isset($this->session_path) && $this->session_path)
			session_save_path($this->session_path);
		
		session_start();
		
		if (!isset($_SESSION['user'])){		//未登录
			$this->user = NULL;
			if ($this->auth_redirect===true) {			
				header("Location: ".site_url());	//跳转到首页
				exit();			
			}
		} else {
			$this->user = $_SESSION['user'];	//将SESSION中的用户属性传递给 $this->user
			
			if ((!isset($this->user['key']) || $this->user['key']!=$this->session_key) && $this->auth_redirect===true) {	//未登录
				header("Location: ".site_url());	//跳转到首页
				exit();			
			}
		}
	}
	
	function logout(){	//登出
		$this->user = NULL;
		$_SESSION['user'] = NULL;
		//清空所有Session中的数据
		$_SESSION = array();
		unset($_SESSION);
	
		// 删除 session cookie.
		// 注意: 这不光光会破坏Session中的数据，连Session也一起被干掉了！
		if (isset($_COOKIE[session_name()])) {
			setcookie(session_name(), '', time()-42000, '/');
		}
		
		// 保险起见，再干掉一次
		session_destroy();
		
		header("Location: ".site_url()); 	//跳转到首页
		
	}
}

?>